package tw.chen.unlock;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider
{
	private String TAG = this.getClass().getName();
	private RemoteViews views;
	private ComponentName provider;
	
	SharedPreferences setting;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	{
		setting = context.getSharedPreferences(Values.SETTING, Values.SETTING_PAGE);
		views = getView(context, R.layout.widget_layout);
		provider = getProvider(context);
		
		boolean state = setting.getBoolean(Values.STATUS, false);
		if (state)
			views.setImageViewResource(R.id.image, R.drawable.enable);
		else
			views.setImageViewResource(R.id.image, R.drawable.disable);
		appWidgetManager.updateAppWidget(provider, views);
	}

	@Override
	public void onReceive(Context context, Intent intent) 
	{
		String action  = intent.getAction();
		Log.i(TAG, action);
		if (action.equals(Values.START_SERVICE))
		{
			setting = context.getSharedPreferences(Values.SETTING, Values.SETTING_PAGE);
			boolean state = setting.getBoolean(Values.STATUS, false);
			Log.i(TAG, "state = " + state);
			Intent service = new Intent();
			service.setClass(context, WidgetService.class);
			if (state)
				context.startService(service);
			else
				context.stopService(service);
		}
		super.onReceive(context, intent);
	}

	private static RemoteViews getView(Context context, int layout_id)
	{
		return new RemoteViews(context.getPackageName(), layout_id);
	}
	
	private static ComponentName getProvider(Context context)
	{
		return new ComponentName(context, WidgetProvider.class);
	}
	
	public static void updateAppWidget(Context context, AppWidgetManager widgetManager, int appWidgetId, boolean isEnable)
	{
		RemoteViews mViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		if (isEnable)
			mViews.setImageViewResource(R.id.image, R.drawable.enable);
		else
			mViews.setImageViewResource(R.id.image, R.drawable.disable);
		widgetManager.updateAppWidget(appWidgetId, mViews);
	}
}
